<template>
  <div>
    <el-form
      label-width="60px"
      :rules="rules"
      :model="phoneLoginInfo"
      ref="formRef"
    >
      <el-form-item label="手机号" prop="phoneNumber" class="phone-title">
        <el-input v-model="phoneLoginInfo.phoneNumber"></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="verificationCode">
        <div class="verification-container">
          <el-input v-model="phoneLoginInfo.verificationCode" show-password>
          </el-input>
          <el-button type="primary" class="fetch-verification-btn">
            获取验证码
          </el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { ElForm } from 'element-plus'
import { useStore } from 'vuex'
import { rules } from '../config/phone.config'
import localCache from '@/utils/cache'
import { defineComponent, reactive, ref } from 'vue'

export default defineComponent({
  setup() {
    const store = useStore()
    const phoneLoginInfo = reactive({
      phoneNumber: localCache.getCache('phoneNumber') ?? '',
      verificationCode: localCache.getCache('verification') ?? ''
    })
    const formRef = ref<InstanceType<typeof ElForm>>()
    const phoneAction = (isKeepPassword: boolean) => {
      formRef.value?.validate((valid) => {
        if (valid) {
          if (isKeepPassword) {
            localCache.setCache('phoneNumber', phoneLoginInfo.phoneNumber)
            localCache.setCache('verification', phoneLoginInfo.verificationCode)
          } else {
            localCache.deleteCache('phoneNumber')
            localCache.deleteCache('verification')
          }
          store.dispatch('loginModule/phoneLoginAction', { ...phoneLoginInfo })
        }
      })
    }
    return {
      phoneLoginInfo,
      formRef,
      phoneAction,
      rules
    }
  }
})
</script>

<style scoped>
.verification-container {
  display: flex;
}
.fetch-verification-btn {
  margin-left: 5px;
}
.phone-title {
  white-space: nowrap;
}
</style>
